using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class DialogueSystem : SingletonMono<DialogueSystem>
{
    [Header("UI组件")]
    [SerializeField] private TMP_Text dialogueUIText;
    [SerializeField] private Image dialogueUIImage;
    //
    [Header("数值")]
    [SerializeField] private float textSpeed;
    private bool textFinished;
    private bool canType;
    private int letter;
    // private bool isDialogue = true;            // 是否可以进行继续对话
    // private int dialogueTextLength;            // 对话文件长度
    private int index;                         // 对话索引


    /// <summary>
    /// 设置对话组件
    /// 场景加载后，由UI系统调用
    /// </summary>
    /// <param name="tMP_Text">UI文本组件</param>
    /// <param name="image">UI任务头像</param>
    public void SetDialogue(TMP_Text tMP_Text, Image image)
    {
        dialogueUIText = tMP_Text;
        dialogueUIImage = image;
    }
    List<String> textList = new List<string>();
    public void Activate()
    {
        dialogueUIText.gameObject.SetActive(true);
        dialogueUIImage.gameObject.SetActive(true);
        StartCoroutine(SetTextUI());
    }
    public void NoActivate()
    {
        index = 0;
        dialogueUIText.gameObject.SetActive(false);
        dialogueUIImage.sprite = null;
        dialogueUIImage.gameObject.SetActive(false);
        textList.Clear();
    }

    //
    public void TextUpdate()
    {
        if(GlobalUIInput.Instance.isDialogue && index == textList.Count)
        {
            index = 0;
            dialogueUIText.gameObject.SetActive(false);
            dialogueUIImage.sprite = null;
            dialogueUIImage.gameObject.SetActive(false);
            return;
        }
        if(GlobalUIInput.Instance.isDialogue)
        {
            if(textFinished && !canType)
                StartCoroutine(SetTextUI());
            else if(!textFinished && !canType)
                canType = true;
        }
    }
    public void GetTextFormFile(TextAsset textAsset, Sprite sprite)
    {
        dialogueUIImage.sprite = sprite;
        textList.Clear();
        index = 0;

        var lineDate = textAsset.text.Split("\n");

        foreach(var line in lineDate)
        {
            textList.Add(line);
        }
    }
    IEnumerator SetTextUI()
    {
        dialogueUIText.text = "";
        textFinished = false;

        letter = 0;
        while(!canType && (letter < textList[index].Length-1))
        {
            dialogueUIText.text += textList[index][letter];
            letter ++;
            yield return new WaitForSeconds(textSpeed);
        }
        dialogueUIText.text = textList[index];
        canType = false;
        textFinished = true;
        index ++;
    }
}
